<template>
	<div class="controls">
		<!-- 
      1.失去焦点时设置值 
      2.绑定data数据
    -->
		<input
			autocomplete="off"
			class="itxt"
			:value="currentValue"
			@blur="setCurrentValue"
		/>
		<button class="plus" @click="currentValue++" :disabled="currentValue >= max">
			+
		</button>
		<button class="mins" @click="currentValue--" :disabled="currentValue <= min">
			-
		</button>
	</div>
</template>

<script>
export default {
	name: "InputNumber",
	props: {
		value: {
			type: Number,
			required: true,
		},
		min: {
			type: Number,
			default: 1,
		},
		max: {
			type: Number,
			default: 100,
		},
	},
	// 因为props不能直接修改，另外定义一个数据
	data() {
		return {
			// 是初始值value,内部就让修改currentValue
			currentValue: this.value,
		};
	},
	methods: {
		setCurrentValue(e) {
			this.currentValue = e.target.value.trim();
		},
	},
	watch: {
		currentValue(newVal, oldVal) {
			// 先拿到最小值和最大值，解构
			const { min, max } = this;
			// newVal是字符串，先转换成number
			let currentValue = +newVal;
			//  2. 输入小于最小值的数，失去焦点变成最小值
			if (currentValue < min) currentValue = min;
			//  3. 输入大于最大值的数，失去焦点变成最大值
			if (currentValue > max) currentValue = max;
			//  4. 输入非数字内容，失去焦点后变成上一次输入的数值
			// 用Number上面的方法isNaN()判断输入的是不是非数值，如果是非数值就取上一次输入的数值
			if (Number.isNaN(currentValue)) currentValue = oldVal;

			// 最后，统一改值(当前组件)
			this.currentValue = currentValue;
			// 还要修改父组件的值,去触发
			this.$emit("input", currentValue);
		},
	},
};
</script>

<style lang="less" scoped>
.controls {
	width: 48px;
	position: relative;
	float: left;
	margin-right: 15px;

	.itxt {
		width: 38px;
		height: 37px;
		border: 1px solid #ddd;
		color: #555;
		float: left;
		border-right: 0;
		text-align: center;
	}

	.plus,
	.mins {
		width: 20px;
		text-align: center;
		height: 20px;
		line-height: 17px;
		background: #f1f1f1;
		color: #666;
		position: absolute;
		right: -8px;
		border: 1px solid #ccc;
    cursor: pointer;
    &[disabled]{
      cursor:not-allowed;
      color: #ccc;
    }
	}

	.mins {
		right: -8px;
		top: 19px;
		border-top: 0;
	}

	.plus {
		right: -8px;
	}
}
</style>
